package com.zxjbyte.yiyi.framework.common.util;

import cn.hutool.core.util.URLUtil;
import lombok.experimental.UtilityClass;
import org.apache.tika.Tika;

import java.net.URI;

/**
 * 扩展URL工具类
 * @Author zhangxingjia
 * @Date 2025/10/13 14:55
 * @Version: 1.0
 */
@UtilityClass
public class URLXUtil extends URLUtil {

    private final Tika tika = new Tika();

    /**
     * 基于文件名检测不实际访问URL
     * 判断文件是否为图片
     * @param urlString
     * @return
     */
    public boolean isImageUrl(String urlString) {
        try {
            String contentType = new Tika().detect(urlString);
            return contentType != null && contentType.startsWith("image/");
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 验证是否是有效URL
     * @param urlString
     * @return
     */
    public boolean isValidURL(String urlString) {
        try {
            URI uri = URLUtil.toURI(urlString, true);

            // 检查协议
            String scheme = uri.getScheme();
            if (scheme == null ||
                    (!scheme.equalsIgnoreCase("http") &&
                            !scheme.equalsIgnoreCase("https") &&
                            !scheme.equalsIgnoreCase("ftp"))) {
                return false;
            }

            // 检查主机名
            return uri.getHost() != null;
        } catch (Exception e) {
            return false;
        }
    }
}
